// plugins/permission.ts
import type { App, Directive, DirectiveBinding } from "vue";
import { usePermissionStore } from "~/stores/permission";
// 权限值类型定义
type PermissionType = string | string[] | ((permissions: string[]) => boolean);
const permissionDirective: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding<PermissionType>) {
    const permissionStore = usePermissionStore();
    const { value, modifiers } = binding;
    // 校验权限
    const hasPermission = permissionStore.hasPermission(value);
    // 处理无权限情况
    if (
      (!modifiers.not && !hasPermission) ||
      (modifiers.not && hasPermission)
    ) {
      el.parentNode?.removeChild(el);
    }
  },
  updated(el: HTMLElement, binding: DirectiveBinding<PermissionType>) {
    if (binding.value !== binding.oldValue) {
      const permissionStore = usePermissionStore();
      const hasPermission = permissionStore.hasPermission(binding.value);
      if (
        (!binding.modifiers.not && !hasPermission) ||
        (binding.modifiers.not && hasPermission)
      ) {
        el.parentNode?.removeChild(el);
      }
    }
  },
};
export default defineNuxtPlugin((nuxtApp) => {
  const app = nuxtApp.vueApp;
  app.directive("permission", permissionDirective);
  app.config.globalProperties.$hasPermission = (permission: PermissionType) => {
    const permissionStore = usePermissionStore();
    return permissionStore.hasPermission(permission);
  };
  nuxtApp.provide("hasPermission", (permission: PermissionType) => {
    const permissionStore = usePermissionStore();
    return permissionStore.hasPermission(permission);
  });
});
